import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, Modal, Image } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import {
  text_check,
  post_axios,
  online_type,
  avm_type_list,
  show_img_url,
  key_find_obj,
} from "../../utils";

export default function ChooseWares(props) {
  const { t } = useTranslation();
  const {
    bar_lib,
    local_company_object,
    choose_goods_show,
    setChoose_goods_show,
    choose_goods_btn_func,
    tableHeight,
    setSpinning,
  } = props;

  // 国内国外判断

  const [kind_page, setKind_page] = useState(1);
  const [kind_rows, setKind_rows] = useState(20);
  const [kind_total, setKind_total] = useState(0);
  const [bar_lib_search, setBar_lib_search] = useState("");
  const [name_search, setName_search] = useState("");
  const [goods_list, setGoods_list] = useState([]);
  // 获取商品库列表
  const get_goods_data = async ({ newPage, newRows, newBar }) => {
    let upMsg = {
      page: newPage ? newPage : kind_page,
      rows: newRows ? newRows : kind_rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      bar_lib: newBar ? newBar : bar_lib_search,
      name_search: name_search,
      barcode_search: "",
    };
    setSpinning(true);
    let res = await post_axios("goods_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    const newArr = res.data_rows.rows.map((item) => {
      item["pic"] = show_img_url(item, local_company_object.company);
      return item;
    });
    setGoods_list(newArr);
    setKind_total(res.data_rows.total);
  };
  const goodsColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("goods.goods_name"),
      dataIndex: "name",
      align: "center",
    },
    {
      title: t("goods.goods_image"),
      align: "center",
      render: (_, record) => (
        <>
          {record.pic && record.pic.length !== 0 ? (
            <Image className="table_img" src={record.pic} />
          ) : (
            ""
          )}
        </>
      ),
    },
    {
      title: t("goods.goods_barcode"),
      dataIndex: "barcode",
      align: "center",
    },
    {
      title: t("goods.commodity_warehouse"),
      align: "center",
      render: (_, record) => (
        <>{key_find_obj(record.bar_lib, goods_kind_list, "kind")["name"]}</>
      ),
    },
    {
      title: t("operate.choose_goods"),
      align: "center",
      render: (_, record) => (
        <Button
          size="small"
          type="primary"
          onClick={() => choose_goods_btn_func(record)}
        >
          {t("assets.select_product")}
        </Button>
      ),
    },
  ];
  // 商品库列表分页器
  const kindPageOnChange = async (page, pageSize) => {
    setKind_page(page);
    setKind_rows(pageSize);
    get_goods_data({ newPage: page, newRows: pageSize });
  };
  const choose_goods_search = async () => {
    setKind_page(1);
    await get_goods_data({ newPage: 1 });
  };

  const barLibOnChange = (value) => {
    setBar_lib_search(value);
    get_goods_data({ newBar: value });
  };
  // 获取分库
  const [goods_kind_list, setGoods_kind_list] = useState([]);
  const get_goods_kind = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_goods_kind",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    const rows = res.data_rows.rows;
    setGoods_kind_list(rows);
    const bar_lib = rows[0].kind;
    setBar_lib_search(bar_lib);
    get_goods_data({ newBar: bar_lib });
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    console.log(bar_lib);
    if (bar_lib) {
      setBar_lib_search(bar_lib);
      get_goods_data({ newBar: bar_lib });
    } else {
      get_goods_kind();
    }
  }, []);
  return (
    <>
      <Modal
        title={t("assets.select_product")}
        open={choose_goods_show}
        onCancel={() => setChoose_goods_show(false)}
        classNames={{
          body: "edit_dialog_body avm_status_dialog",
          wrapper: "noFooterFullscreen",
        }}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <div className="dialog_btn_box">
          {bar_lib ? (
            ""
          ) : (
            <div className="ipt_box">
              <div className="ipt_box_title">
                {t("goods.commodity_warehouse")}
              </div>
              <Select
                size="small"
                placeholder=" "
                fieldNames={{
                  value: "kind",
                  label: "name",
                }}
                options={goods_kind_list}
                value={bar_lib_search}
                onChange={barLibOnChange}
              />
            </div>
          )}
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_name")}</div>
            <Input
              value={name_search}
              onChange={(e) => setName_search(e.target.value)}
              size="small"
            />
          </div>
          <Button
            size="small"
            shape="circle"
            icon={<SearchOutlined />}
            onClick={choose_goods_search}
          />
        </div>
        <Table
          dataSource={goods_list}
          size="small"
          bordered
          columns={goodsColumns}
          rowKey="barcode"
          virtual
          scroll={{
            y: tableHeight + 80,
          }}
          rowHoverable={false}
          pagination={{
            defaultCurrent: kind_page,
            defaultPageSize: kind_rows,
            size: "small",
            current: kind_page,
            total: kind_total,
            responsive: true,
            showTotal: (total) =>
              text_check({
                msg_cn: `共 ${total} 条`,
                msg_en: `Total ${total} items`,
              }),
            onChange: kindPageOnChange,
          }}
        />
      </Modal>
    </>
  );
}
